package com.boss.salary.controller;


import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.IAgencyVerifyDao;
import com.boss.salary.dto.PersonBatchOperateDTO;
import com.boss.salary.dto.PersonOperateAndSalaryDTO;
import com.boss.salary.entity.OperrateLogs;
import com.boss.salary.entity.PersonOperate;
import com.boss.salary.service.IOperrateLogsService;
import com.boss.salary.service.IPersonOperateService;
import com.boss.salary.utils.CompareUtils;
import com.boss.salary.vo.ComparisonResultVo;
import com.boss.sys.ca.user.dto.UserDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.http.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/personOperateController", produces = MediaType.APPLICATION_JSON_VALUE)
public class PersonOperateController extends BasicinfoBaseController {
    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(PersonOperateController.class);


    @Autowired
    private IPersonOperateService service;
    @Autowired
    private IAgencyVerifyDao agencyVerifyDao;
    @Autowired
    private IOperrateLogsService iOperrateLogsService;
    /**
     * 查询 人员信息操作表数据分页
     * @param offset
     * @param limit
     * @return
     */
    @GetMapping("/queryPersonOperatePage")
    public ApiResultDTO queryPersonOperatePage(@RequestParam(value = "offset") String offset,
                                           @RequestParam(value = "limit") String limit) {
        try {
            Map<String, Object> parameters = new HashMap<>(8);
            parameters.put("offset", offset);
            parameters.put("limit", limit);

            PaginationDTO paginationDTO = PageUtils.buildPaginationDTO(parameters);
            PageDTO<PersonOperate> pageDTO = service.queryPersonOperatePage(paginationDTO);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败！");
        }
    }

    /**
     * 新增、修改、调出、调入、消减 人员信息操作表数据
     * @param personOperate
     * @return
     */
    @PostMapping("/savePersonOperate")
    public ApiResultDTO savePersonOperate(@RequestHeader("X-Token") String tokenid,
                                          @RequestBody PersonOperate personOperate) {
        try {
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            personOperate.setMofDivCode(userDTO.getProvince());
            ArrayList<Object> personIds = new ArrayList<>();
            String is_deleted = agencyVerifyDao.selectStateByAgencyId(personOperate.getAgencyId(), "is_deleted")
                    .get("is_deleted").toString();
            if(SystemDictConstant.IS_DELETED_STR.equals(is_deleted)){
                return ApiResultDTO.error(ERROR_RSCODE, "单位已退出统发！无法进行人员操作！请联系运维人员恢复统发单位！");
            }
            //新增人
            if (SystemDictConstant.ADD_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--新增");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //调出
            }else if(SystemDictConstant.OUT_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--调出");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                if (StringUtils.isEmpty(personOperate.getOutToAgency())) {
                    throw new AppRuntimeException("去向单位不存在,请选择去向单位!");
                }
                //通过单位id查询去向单位月份 如果两个月份不一致不允许调出
                PersonOperate agencySalaryMonth=service.getSalaryMonth(personOperate.getAgencyId());
                if(!agencySalaryMonth.getSalaryMonth().equals(personOperate.getOutAgencySalaryMonth())){
                    throw new AppRuntimeException("去向单位和本单位月份不一致禁止调出!");
                }
                //消减
            }else if(SystemDictConstant.DELETE_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--消减");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //调入
            }else if(SystemDictConstant.IN_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--调入");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //更新
            }else{
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--更新");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //获取原人员信息
                PersonOperate oldPersonOperate=service.getOldPersonOperate(personOperate.getPersonId());
                // 比对不一致的值
                List<ComparisonResultVo> CompareList = CompareUtils.compareObj(oldPersonOperate, personOperate);
                List<ComparisonResultVo> WithoutCompareList=new ArrayList<>();
                if(!CollectionUtils.isEmpty(CompareList)) {
                    for (ComparisonResultVo comparisonResultVo1 : CompareList) {
                        if ("operateCode".equals(comparisonResultVo1.getField()) || "createTime".equals(comparisonResultVo1.getField())
                                || "id".equals(comparisonResultVo1.getField())
                                || "updateTime".equals(comparisonResultVo1.getField())
                                || "verifyState".equals(comparisonResultVo1.getField())
                                || "salaryMonth".equals(comparisonResultVo1.getField())
                                || "isReal".equals(comparisonResultVo1.getField())
                                || "existsFile".equals(comparisonResultVo1.getField())
                                || "deptId".equals(comparisonResultVo1.getField())
                                ||"startDate".equals(comparisonResultVo1.getField())) {
                            WithoutCompareList.add(comparisonResultVo1);
                            continue;
                        }

                    }
                    CompareList.removeAll(WithoutCompareList);
                }
                if(CollectionUtils.isEmpty(CompareList)) {
                    return ApiResultDTO.success(null, "无修改");
                }

            }

            String personid= StringUtils.join(personIds,",");
            operrateLogs.setPersonId(personid);
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            ApiResultDTO apiResultDTO= service.savePersonOperate(personOperate);
            return apiResultDTO;
        }catch (AppRuntimeException e){

            logger.error("新增人员信息: {}", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        } catch (Exception e) {
            logger.error("新增 人员信息操作表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "保存失败!");
        }
    }

    /**
     * 新增、修改、调出、调入、消减 人员信息操作表数据
     * @param personOperateAndSalary
     * @return
     */
    @PostMapping("/savePersonOperateAndSalary")
    public ApiResultDTO savePersonOperateAndSalary(@RequestHeader("X-Token") String tokenid,
                                          @RequestBody PersonOperateAndSalaryDTO personOperateAndSalary) {
        try {
            //获取人员信息
            PersonOperate personOperate=personOperateAndSalary.getOperate();
            personOperateAndSalary.getSalary().setPersonId(personOperate.getPersonId());
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            personOperate.setMofDivCode(userDTO.getProvince());
            ArrayList<Object> personIds = new ArrayList<>();
            String is_deleted = agencyVerifyDao.selectStateByAgencyId(personOperate.getAgencyId(), "is_deleted")
                    .get("is_deleted").toString();
            if(SystemDictConstant.IS_DELETED_STR.equals(is_deleted)){
                return ApiResultDTO.error(ERROR_RSCODE, "单位已退出统发！无法进行人员操作！请联系运维人员恢复统发单位！");
            }
            //新增人
            if (SystemDictConstant.ADD_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--新增");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //调出
            }else if(SystemDictConstant.OUT_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--调出");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                if (StringUtils.isEmpty(personOperate.getOutToAgency())) {
                    throw new AppRuntimeException("去向单位不存在,请选择去向单位!");
                }
                //通过单位id查询去向单位月份 如果两个月份不一致不允许调出
                PersonOperate agencySalaryMonth=service.getSalaryMonth(personOperate.getAgencyId());
                if(!agencySalaryMonth.getSalaryMonth().equals(personOperate.getOutAgencySalaryMonth())){
                    throw new AppRuntimeException("去向单位和本单位月份不一致禁止调出!");
                }
                //消减
            }else if(SystemDictConstant.DELETE_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--消减");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //调入
            }else if(SystemDictConstant.IN_PERSON.equals(personOperate.getOperateCode())){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--调入");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //更新
            }else{
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--更新");
                operrateLogs.setAgencyId(personOperate.getAgencyId());
                personIds.add(personOperate.getPersonId());
                //获取原人员信息
                PersonOperate oldPersonOperate=service.getOldPersonOperate(personOperate.getPersonId());
                // 比对不一致的值
                List<ComparisonResultVo> CompareList = CompareUtils.compareObj(oldPersonOperate, personOperate);
                List<ComparisonResultVo> WithoutCompareList=new ArrayList<>();
                if(!CollectionUtils.isEmpty(CompareList)) {
                    for (ComparisonResultVo comparisonResultVo1 : CompareList) {
                        if ("operateCode".equals(comparisonResultVo1.getField()) || "createTime".equals(comparisonResultVo1.getField())
                                || "id".equals(comparisonResultVo1.getField())
                                || "updateTime".equals(comparisonResultVo1.getField())
                                || "verifyState".equals(comparisonResultVo1.getField())
                                || "salaryMonth".equals(comparisonResultVo1.getField())
                                || "isReal".equals(comparisonResultVo1.getField())
                                || "existsFile".equals(comparisonResultVo1.getField())
                                || "deptId".equals(comparisonResultVo1.getField())
                                ||"startDate".equals(comparisonResultVo1.getField())) {
                            WithoutCompareList.add(comparisonResultVo1);
                            continue;
                        }

                    }
                    CompareList.removeAll(WithoutCompareList);
                }
                if(CollectionUtils.isEmpty(CompareList)) {
                    return ApiResultDTO.success(null, "无修改");
                }

            }

            String personid= StringUtils.join(personIds,",");
            operrateLogs.setPersonId(personid);
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            service.savePersonOperateAndSalary(personOperateAndSalary,userDTO);

            return ApiResultDTO.success(null, "保存成功");
        }catch (AppRuntimeException e){

            logger.error("新增人员信息: {}", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        } catch (Exception e) {
            logger.error("新增 人员信息操作表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "保存失败!");
        }
    }
    /**
     * 批量操作人员信息操作表数据
     * @param personBatchOperate
     * @return
     */
    @PostMapping("/savePersonOperateBatch")
    public ApiResultDTO savePersonOperateBatch(@RequestHeader("X-Token") String tokenid,
                                          @RequestBody PersonBatchOperateDTO personBatchOperate) {
        try {
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            List<PersonOperate> operateList=personBatchOperate.getPersonOperateList();
            if(CollectionUtils.isEmpty(operateList)){
                return ApiResultDTO.error(ERROR_RSCODE, "未传入操作数据！");
            }
            ArrayList<Object> personIds = new ArrayList<>();
            String is_deleted = agencyVerifyDao.selectStateByAgencyId(personBatchOperate.getAgencyId(), "is_deleted")
                    .get("is_deleted").toString();
            if(SystemDictConstant.IS_DELETED_STR.equals(is_deleted)){
                return ApiResultDTO.error(ERROR_RSCODE, "单位已退出统发！无法进行人员操作！请联系运维人员恢复统发单位！");
            }
            //新增人
            if (SystemDictConstant.ADD_PERSON.equals(personBatchOperate.getOperateCode())){
                operrateLogs.setOperateName("批量人员信息维护--人员变动编辑--新增");
                operrateLogs.setAgencyId(personBatchOperate.getAgencyId());

                //调出
            }else if(SystemDictConstant.OUT_PERSON.equals(personBatchOperate.getOperateCode())){
                operrateLogs.setOperateName("批量人员信息维护--人员变动编辑--调出");
                operrateLogs.setAgencyId(personBatchOperate.getAgencyId());

                if (StringUtils.isEmpty(personBatchOperate.getOutToAgency())) {
                    throw new AppRuntimeException("去向单位不存在,请选择去向单位!");
                }
                //通过单位id查询去向单位月份 如果两个月份不一致不允许调出
                PersonOperate agencySalaryMonth=service.getSalaryMonth(personBatchOperate.getAgencyId());
                if(!agencySalaryMonth.getSalaryMonth().equals(personBatchOperate.getOutAgencySalaryMonth())){
                    throw new AppRuntimeException("去向单位和本单位月份不一致禁止调出!");
                }
                //消减
            }else if(SystemDictConstant.DELETE_PERSON.equals(personBatchOperate.getOperateCode())){
                operrateLogs.setOperateName("批量人员信息维护--人员变动编辑--消减");
                operrateLogs.setAgencyId(personBatchOperate.getAgencyId());

                //调入
            }else if(SystemDictConstant.IN_PERSON.equals(personBatchOperate.getOperateCode())){
                operrateLogs.setOperateName("批量人员信息维护--人员变动编辑--调入");
                operrateLogs.setAgencyId(personBatchOperate.getAgencyId());

                //更新
            }else{
                operrateLogs.setOperateName("批量人员信息维护--人员变动编辑--更新");
                operrateLogs.setAgencyId(personBatchOperate.getAgencyId());
            }
            personIds.add(operateList.stream().map(PersonOperate::getPersonId).collect(Collectors.toList()));
            String personid= StringUtils.join(personIds,",");
            operrateLogs.setPersonId(personid);
            iOperrateLogsService.saveOperrateLogs(operrateLogs);
            ApiResultDTO apiResultDTO=ApiResultDTO.success(null, "保存成功");
            for(PersonOperate op:operateList){
                op.setOperateCode(personBatchOperate.getOperateCode());
                op.setAgencyId(personBatchOperate.getAgencyId());
                op.setOutToAgency(personBatchOperate.getOutToAgency());
                op.setMofDivCode(userDTO.getProvince());
                op.setDeleteType(personBatchOperate.getDeleteType());
                apiResultDTO=service.savePersonOperate(op);
            }
            return apiResultDTO;
        }catch (AppRuntimeException e){

            logger.error("批量人员信息操作: {}", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        } catch (Exception e) {
            logger.error("批量人员信息操作表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "保存失败!");
        }
    }
    /**
     * 更新 人员信息操作表数据
     * @param personOperate
     * @return
     */
    @PostMapping("/updatePersonOperate")
    public ApiResultDTO updatePersonOperate(@RequestBody PersonOperate personOperate) {
        try {
            service.updatePersonOperate(personOperate);
            return ApiResultDTO.success(null, "更新成功");
        } catch (Exception e) {
            logger.error("更新 人员信息操作表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "更新失败！");
        }
    }

    /**
     * 删除 人员信息操作表数据
     * @param id
     * @return
     */
    @DeleteMapping("/deletePersonOperate/{id}")
    public ApiResultDTO deletePersonOperate(@PathVariable("id") String id) {
        try {
            service.deletePersonOperate(id);
            return ApiResultDTO.success(null, "删除成功");
        } catch (Exception e) {
            logger.error("删除 人员信息操作表数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "删除失败！");
        }
    }

    /**
     * 操作表最新的人员数据  -- 身份证核对
     * @param page
     * @param limit
     * @param flag
     * @param type
     * @return
     */
    @GetMapping("/getPersonOperatePage")
    public ApiResultDTO getPersonOperatePage(@RequestHeader("X-Token") String tokenid,
                                             @RequestParam(value = "page") String page,
                                             @RequestParam(value = "limit") String limit,
                                             @RequestParam(value = "flag") String flag,
                                             @RequestParam(value = "type") String type,
                                             @RequestParam(value = "agencyId") String agencyId,
                                             @RequestParam(value = "idLength", required = false) String idLength,
                                             @RequestParam(value = "gzlb", required = false) String gzlb){

        try {
            UserDTO userDTO = getUser(tokenid);
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("flag", flag);
            queryParam.put("type", type);
            queryParam.put("agencyId", agencyId);
            queryParam.put("idLength", idLength);
            queryParam.put("gzlb", gzlb);
            queryParam.put("mofDivCode",userDTO.getProvince());
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<PersonOperate> pageDTO = service.getPersonOperatePage(paginationDTO, queryParam);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败！");
        }
    }

    /**
     * 操作表最新的人员数据 -- 人员变动编辑
     * @param page
     * @param limit
     * @param flag
     * @return
     */
    @GetMapping("/getPersonInfoChangeOperatePage")
    public ApiResultDTO getPersonInfoChangeOperatePage(@RequestHeader("X-Token") String tokenid,
                                                       @RequestParam(value = "page") String page,
                                                     @RequestParam(value = "limit") String limit,
                                                     @RequestParam(value = "flag") String flag,
                                                     @RequestParam(value = "deptId", required = false) String deptid,
                                                     @RequestParam(value = "agencyId") String agencyId,
                                                     @RequestParam(value = "meritPayCode", required = false) String meritPayCode,
                                                     @RequestParam(value = "posCode", required = false) String posCode,
                                                     @RequestParam(value = "grCode", required = false) String grCode,
                                                     @RequestParam(value = "personName", required = false) String personName,
                                                     @RequestParam(value = "idenNo", required = false) String idenNo,
                                                     @RequestParam(value = "state", required = false) String state ){

        try {
            UserDTO userDTO = getUser(tokenid);
            Map<String, Object> queryParam = new HashMap<>(7);
            queryParam.put("flag", flag);
            queryParam.put("deptid", deptid);
            queryParam.put("agencyId", agencyId);
            queryParam.put("meritPayCode", meritPayCode);
            queryParam.put("posCode", posCode);
            queryParam.put("grCode", grCode);
            queryParam.put("personName", personName);
            queryParam.put("idenNo", idenNo);
            queryParam.put("state", state);
            queryParam.put("mofDivCode",userDTO.getProvince());
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<PersonOperate> pageDTO = service.getPersonInfoChangeOperatePage(paginationDTO, queryParam);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败！");
        }
    }

    /**
     * 身份证核对数据
     * @param list
     * @return
     */
    @PostMapping("/checkPassPersonOperate")
    public ApiResultDTO checkPassPersonOperate(@RequestBody List<PersonOperate> list){
        try {
            service.checkPassPersonOperate(list);
            return ApiResultDTO.success(null, "核对成功");
        } catch (Exception e) {
            logger.error("身份证单位核对发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "核对失败！");
        }
    }

    /**
     * 撤回身份证核对数据
     * @param list
     * @return
     */
    @PostMapping("undoCheckPersonOperate")
    public ApiResultDTO undoCheckPersonOperate(@RequestBody List<PersonOperate> list){
        try {
            service.undoCheckPersonOperate(list);
            return ApiResultDTO.success(null, "撤回成功");
        } catch (Exception e) {
            logger.error("撤回身份证单位核对发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤回失败！");
        }
    }

    /**
     * 修改身份证号码
     * @param personOperate
     * @return
     */
    @PostMapping("/updatePersonOperateID")
    public ApiResultDTO updatePersonOperateID(@RequestBody PersonOperate personOperate){
        try {
            service.updatePersonOperateID(personOperate);
            return ApiResultDTO.success(null, "修改成功");
        } catch (Exception e) {
            logger.error("修改身份证单位核对发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "修改失败！");
        }
    }

    /**
     * 撤销修改身份证修改
     * @param personOperate
     * @return
     */
    @PostMapping("/undoUpdatePersonOperateID")
    public ApiResultDTO undoUpdatePersonOperateID(@RequestBody PersonOperate personOperate){
        try {
            service.undoCheckPersonOperateID(personOperate);
            return ApiResultDTO.success(null, "撤回成功");
        } catch (Exception e) {
            logger.error("撤回身份证单位核对发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤回失败！");
        }
    }

    /**
     * 送审
     * @param list
     * @return
     */
    @PostMapping("/forReviewPersonOperateList")
    public ApiResultDTO forReviewPersonOperateList(@RequestBody List<PersonOperate> list){
        try {
            service.forReviewPersonOperate(list);
            return ApiResultDTO.success(null, "送审成功");
        } catch (Exception e) {
            logger.error("  身份证单位信息送审发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "送审失败！");
        }
    }

    /**
     * 撤销送审
     * @param list
     * @return
     */
    @PostMapping("/undoForReviewPersonOperateList")
    public ApiResultDTO undoForReviewPersonOperateList(@RequestBody List<PersonOperate> list){
        try {
            service.undoForReviewPersonOperate(list);
            return ApiResultDTO.success(null, "撤回成功");
        } catch (Exception e) {
            logger.error("  身份证单位信息撤回送审发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤回失败！");
        }
    }

    /**
     * 人员编辑变动送审
     * @param list
     * @return
     */
    @PostMapping("/submitPersonOperateList")
    public ApiResultDTO submitPersonOperateList(@RequestBody List<PersonOperate> list){
        try {
            service.submitPersonOperateList(list);
            return ApiResultDTO.success(null, "送审成功");
        } catch (Exception e) {
            logger.error("  人员变动送审发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "送审失败！");
        }
    }
    /**
     * 人员变动撤销送审
     * @param list
     * @return
     */
    @PostMapping("/undoSubmitPersonOperateList")
    public ApiResultDTO undoSubmitPersonOperateList(@RequestBody List<PersonOperate> list){
        try {
            service.undoSubmitPersonOperateList(list);
            return ApiResultDTO.success(null, "撤回成功");
        } catch (Exception e) {
            logger.error("  人员变动撤回送审发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤回失败！");
        }
    }

    /**
     * 撤销操作
     * 撤销调出、撤销调入、撤销消减、撤销修改、删除
     * @param list
     * @return
     */
    @PostMapping("revokeOperate")
    public ApiResultDTO revokeOperate(@RequestBody List<PersonOperate> list){
        try {
            service.revokeOperate(list);
            return ApiResultDTO.success(null, "撤回成功");
        } catch (Exception e) {
            logger.error("撤销操作对发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤回失败！");
        }
    }

    /**
     * 退回
     * @param list
     * @return
     */
    @PostMapping("rejectOperate")
    public ApiResultDTO rejectOperate(@RequestBody List<PersonOperate> list){
        try {
            service.rejectOperate(list);
            return ApiResultDTO.success(null, "撤回成功");
        } catch (Exception e) {
            logger.error("退回操作发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "退回失败！");
        }
    }

    /**
     * 人员变动审核-审核通过
     * @param list
     * @return
     */
    @PostMapping("personApproved")
    public ApiResultDTO personApproved(@RequestHeader("X-Token") String tokenid,
                                       @RequestBody List<PersonOperate> list){
        try {
            UserDTO userDTO = getUser(tokenid);
            for (PersonOperate personOperate : list) {
                personOperate.setMofDivCode(userDTO.getProvince());
            }
            service.personApproved(list);
            return ApiResultDTO.success(null, "人员变动审核-审核通过成功");
        } catch (Exception e) {
            logger.error("人员变动审核-审核通过操作发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "审核失败！");
        }
    }

    /**
     * 人员变动审核-撤销审核
     * @param personOperate
     * @return
     */
    @PostMapping("rejectPersonApproved")
    public ApiResultDTO rejectPersonApproved(@RequestHeader("X-Token") String tokenid,
                                             @RequestBody PersonOperate personOperate){
        try {
            UserDTO userDTO = getUser(tokenid);
            String operateCode = personOperate.getOperateCode();
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setUserAgencyId(userDTO.getAgency());

            ArrayList<Object> personIds = new ArrayList<>();
            String is_deleted = agencyVerifyDao.selectStateByAgencyId(personOperate.getAgencyId(), "is_deleted")
                    .get("is_deleted").toString();
            if(SystemDictConstant.IS_DELETED_STR.equals(is_deleted)){
                return ApiResultDTO.error(ERROR_RSCODE, "单位已退出统发！无法撤销变动！如需撤销请联系运维人员恢复统发单位！");
            }
            //新增
            if(SystemDictConstant.ADD_PERSON.equals(operateCode)){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--撤销新增");
                //人员消减
            }else if(SystemDictConstant.DELETE_PERSON.equals(operateCode)){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--撤销消减");
                //人员调入
            }else if(SystemDictConstant.IN_PERSON.equals(operateCode)){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--撤销调入");
                //人员调出
            }else if(SystemDictConstant.OUT_PERSON.equals(operateCode)){
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--撤销调出");
                //人员编辑
            }else{
                operrateLogs.setOperateName("人员信息维护--人员变动编辑--撤销更新");
            }
            operrateLogs.setAgencyId(personOperate.getAgencyId());
            personIds.add(personOperate.getPersonId());
            String personid= StringUtils.join(personIds,",");
            operrateLogs.setPersonId(personid);
            iOperrateLogsService.saveOperrateLogs(operrateLogs);
            personOperate.setMofDivCode(userDTO.getProvince());
            service.rejectPersonApproved(personOperate);
            return ApiResultDTO.success("人员变动审核-撤销审核成功");
        } catch (AppRuntimeException e){
            logger.error("人员变动审核-撤销审核操作发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        } catch (Exception e) {
            logger.error("人员变动审核-撤销审核操作发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销审核失败！");
        }
    }

    /**
     * 人员变动审核-撤销审核
     * @param list
     * @return
     */
    @PostMapping("revokeVerify")
    public ApiResultDTO revokeVerify(@RequestBody List<PersonOperate> list){
        try {
            service.revokeVerify(list);
            return ApiResultDTO.success(null, "人员变动审核-撤销审核成功");
        } catch (Exception e) {
            logger.error("人员变动审核-撤销审核操作发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销失败！");
        }
    }

    /**
     * 获取在职和离职人数
     * @return
     */
    @GetMapping("/getStateNum")
    public ApiResultDTO getStateNum(@RequestParam(value = "flag") String flag,
                                    @RequestParam(value = "agencyId") String agencyId,
                                    @RequestParam(value = "meritPayCode", required = false) String meritPayCode,
                                    @RequestParam(value = "posCode", required = false) String posCode,
                                    @RequestParam(value = "grCode", required = false) String grCode,
                                    @RequestParam(value = "personName", required = false) String personName,
                                    @RequestParam(value = "idenNo", required = false) String idenNo) {
        try {
            Map<String, Object> queryParam = new HashMap<>(7);
            queryParam.put("flag", flag);
            queryParam.put("agencyId", agencyId);
            queryParam.put("meritPayCode", meritPayCode);
            queryParam.put("posCode", posCode);
            queryParam.put("grCode", grCode);
            queryParam.put("personName", personName);
            queryParam.put("idenNo", idenNo);
            Map<String, Object> map = service.getStateNum(queryParam);
            return ApiResultDTO.success(map, null);
        } catch (Exception e) {
            logger.error("获取在职和离职人数数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败！");
        }
    }

    /**
     * 身份证审核
     * @return
     */
    @PostMapping("/auditPassPersonOperate")
    public ApiResultDTO auditPassPersonOperate(@RequestBody List<PersonOperate> list){
        try {
            service.auditPassPersonOperate(list);
            return ApiResultDTO.success(null, "审核成功");
        } catch (Exception e) {
            logger.error("身份证审核发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "审核失败！");
        }
    }
    /**
     * 身份证送审退回
     * @param list
     * @return
     */
    @PostMapping("/undoAuditPassPerson")
    public ApiResultDTO undoAuditPassPerson(@RequestBody List<PersonOperate> list){
        try {
            service.undoAuditPassPersonOperate(list);
            return ApiResultDTO.success(null, "退回回成功");
        } catch (Exception e) {
            logger.error("退回操作发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "退回失败！");
        }
    }

    /**
     * 获取人员的变更记录类型
     * @param agencyId
     * @param personId
     * @return
     */
    @GetMapping("/getPersonOperateRecordType")
    public ApiResultDTO getPersonOperateRecordType(@RequestParam(value = "agencyId") String agencyId,
                                                   @RequestParam(value = "personId") String personId,
                                                   @RequestParam(value = "personState",required = false) String personState){
        try {
            List<ComparisonResultVo> result = service.getPersonOperateRecordType(agencyId, personId,personState);
            return ApiResultDTO.success(result);
        } catch (Exception e) {
            logger.error("获取人员的变更记录发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败！");
        }
    }

    /**
     * 获取人员的变更记录
     * @param agencyId
     * @param personId
     * @return
     */
    @GetMapping("/getPersonOperateRecord")
    public ApiResultDTO getPersonOperateRecord(@RequestParam(value = "agencyId") String agencyId,
                                               @RequestParam(value = "personId") String personId,
                                               @RequestParam(value = "operateCode") String operateCode,
                                               @RequestParam(value = "creatTime") String creatTime){
        try {
            List<ComparisonResultVo> result = service.getPersonOperateRecord(agencyId, personId, operateCode,creatTime);
            return ApiResultDTO.success(result);
        } catch (Exception e) {
            logger.error("获取人员的变更记录发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败！");
        }
    }

    @PostMapping("/undoAuditPersonOperateList")
     public ApiResultDTO undoAuditPersonOperateList(@RequestBody List<PersonOperate> list) {
        try {
            service.undoAuditPersonOperateList(list);
            return ApiResultDTO.success(null, "撤销审核成功");
        } catch (Exception e) {
            logger.error("撤销审核操作发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销失败！");
        }
    }


    /**
     * 获取人员变动情况
     * @param page
     * @param limit
     * @param agencyId
     * @return
     */
    @GetMapping("/getPersonChangeList")
    public ApiResultDTO getPersonChangeList(@RequestParam("page") String page,
                                            @RequestParam("limit") String limit,
                                            @RequestParam("agencyId") String agencyId) {
        try {
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("agencyId", agencyId);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<PersonOperate> pageDTO = service.getPersonChangeList(paginationDTO, queryParam);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败！");
        }
    }
    @GetMapping("/agencyVerifyStatus")
    public ApiResultDTO initPerson(@RequestHeader("X-Token") String tokenid,
                                   @RequestParam("agencyId") String agencyId){
        try {
            Map<String, Object> map = agencyVerifyDao.selectStateByAgencyId(agencyId, "is_deleted");
            String is_deleted= map.get("is_deleted")==null?SystemDictConstant.IS_DELETED_STR:map.get("is_deleted").toString();
            return ApiResultDTO.success(is_deleted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ApiResultDTO.success(SystemDictConstant.IS_DELETED_STR);
    }

}
